package cn.sykj.car.controller;


import cn.sykj.car.entity.OperationLog;
import cn.sykj.car.entity.Users;
import cn.sykj.car.utils.HttpUtils;
import cn.sykj.car.utils.Utils;
import cn.sykj.car.utils.excel.ExcelUtils;
import cn.sykj.car.vo.ResponseMessageVO;
import org.apache.shiro.SecurityUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 过电流
 * </p>
 *
 * @author yixu
 * @since 2018-12-22
 */
public class BaseController {

    @Resource
    private cn.sykj.car.service.IUsersService iSysUsersService;

    @Resource
    private cn.sykj.car.service.IOperationLogService iSysOperationLogService;
    @Resource
    HttpServletRequest request;

    protected void exportExcel(HttpServletResponse response, List list, String fileName) {

        response.setContentType("octets/stream");
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8") + ".xlsx");
            OutputStream out = response.getOutputStream();
//            ExcelUtils.writeExcelToStreamTest(response, out, list, null);
            ExcelUtils.writeExcelToStream(out, list, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void writeLog(String operation) {

        Object obj = SecurityUtils.getSubject().getPrincipal();
        // 获取登陆系统用户名，存入日志
        Users users = iSysUsersService.getUserByName(obj.toString());
        // 插入日志
        OperationLog log = new OperationLog();
        log.setOperationUserId(users.getId());
        log.setOperationUserName(users.getUserName());
        log.setOperationDate(new Date());
        log.setRemoteIp(HttpUtils.getIPAddress(request));
//        log.setRemoteIp("localhost");
        log.setOparationEvent(operation);

        iSysOperationLogService.save(log);
    }

    /**
     * 运营需要，细化操作日志
     */
    protected void writeLog2Manager(ResponseMessageVO responseMessageVO){
        Object obj = SecurityUtils.getSubject().getPrincipal();
        // 获取登录系统用户名，存入日志
        Users users = iSysUsersService.getUserByName(obj.toString());

        // 插入日志
        OperationLog log = new OperationLog();
        log.setOperationUserId(users.getId());
        log.setOperationUserName(users.getUserName());
        log.setOperationDate(new Date());
        log.setRemoteIp(HttpUtils.getIPAddress(request));
        log.setOparationEvent(responseMessageVO.getRetMsg());
        log.setOperationType(responseMessageVO.getRetType());
        iSysOperationLogService.save(log);
    }

    protected void writeLog(String operation, Integer userId, String userName) {

        // 插入日志
        OperationLog log = new OperationLog();
        log.setOperationUserId(userId);
        log.setOperationUserName(userName);
        log.setOperationDate(new Date());
        log.setRemoteIp(HttpUtils.getIPAddress(request));
        log.setOparationEvent(operation);

        iSysOperationLogService.save(log);
    }

//    @ExceptionHandler(value = Exception.class)
//    public
//    @ResponseBody
//    ResponseBean handleBaseException(Exception e) {
//        if (e instanceof BusinessException) {
//            return new ResponseBean(((BusinessException) e).getCode() + "", ((BusinessException) e).getMsg(), null);
//        }
//        if (e instanceof JsonParseException) {
//            return new ResponseBean(StatusCode.OK_FAIL.getCode() + "", "请联系管理员，json解析异常：" + e.getMessage(), null);
//        }
//        if (e instanceof UnauthorizedException || e instanceof AuthorizationException) {
//            return new ResponseBean(StatusCode.UN_AUTHORIZED.getCode()+"", StatusCode.UN_AUTHORIZED.getMsg(), null);
//        }
//        e.printStackTrace();
//        return new ResponseBean(StatusCode.OK_FAIL.getCode() + "", "请联系管理员，系统异常：" + e.getMessage(), null);
//    }


    public
    @ResponseBody
    cn.sykj.car.common.ResponseBean throwParamException(BindingResult bindingResult) {

        String errorStr = "";
        if (Utils.notEmpty(bindingResult)) {
            List<ObjectError> allErr = bindingResult.getAllErrors();
            if (allErr.size() > 0) {
                for (ObjectError objectError : allErr) {
                    errorStr = errorStr.concat(objectError.getDefaultMessage()).concat(";");
                }
            }
        }
        return new cn.sykj.car.common.ResponseBean(cn.sykj.car.common.StatusCode.OK_FAIL.getCode() + "", errorStr, "");
    }
}
